<script setup lang="ts">
import useStore from '@/store/index'
import {ComputedRef, reactive, computed, ref} from 'vue'
import {provinceAndCityData, codeToText} from 'element-china-area-data'
import {usePagination} from "@/hooks/pagination.ts";
import {SupervisionDataDto} from "@/ts/entityTypes.ts"
import {getSupervisionDataApi} from "@/api/supervisionDataApi.ts";
import {ElMessage} from "element-plus";
import SupervisionPreview from "@/components/supervision/SupervisionPreview.vue";

const store = useStore()
store.homeTitle = '公众监督数据列表'

let selectForm = reactive({
  province: '',
  city: '',
  estimatedLevel: 0,
  isAssigned: 0,
  dateRange: ''
})
let tableData = reactive<Array<SupervisionDataDto>>([])
const showPreview = ref(false)
const color = ref('#33c2f1')
let chosenSupervisorId = ref<string>('')
let chosenSupervisionIsAssigned = ref<number>(1)

const emit = defineEmits<{
  (e: 'getAddress', data: {
    code: string[] //区域码
    name: string[] //汉字
    isComplete: boolean  //是否选择完整，方便校验
  }): void
}>()


let address = reactive<{
  province: string
  city: string
}>({
  province: '',
  city: ''
})

interface AreaList {
  value: string
  label: string
}

const cityList: ComputedRef<AreaList[]> = computed((): AreaList[] => {
  if (!address.province) { return [] }
  let temp = provinceAndCityData.find((item: any) => {
    return item.value == address.province
  })
  return temp?.children ? temp.children : []
})


const handleProvinceSelect = () => {
  address.city = ''
  emit('getAddress', {
    code: [address.province], //区域码
    name: [codeToText[address.province]], //汉字
    isComplete: false
  })
}


const estimatedOptions = [
  { value: 0, label: '全部' , color: '#33c2f1'},
  { value: 1, label: '优（一）' , color: '#00ff00'},
  { value: 2, label: '良（二）' , color: '#ffff00'},
  { value: 3, label: '轻度污染（三）' , color: '#ff7f00'},
  { value: 4, label: '中度污染（四）' , color: '#ff0000'},
  { value: 5, label: '重度污染（五）' , color: '#8b00ff'},
  { value: 6, label: '严重污染（六）' , color: '#8b0000'}
]

const changeLevel = () =>{
  color.value = estimatedOptions.find((item)=>{
    return item.value == selectForm.estimatedLevel
  })?.color ?? ''
  console.log(color.value)
}

const shortcuts = [
  {
    text: '这个月',
    value: () => {
      const end = new Date()
      const start = new Date(new Date().getFullYear(), new Date().getMonth())
      return [start, end]
    }
  },
  {
    text: '今年',
    value: () => {
      const end = new Date()
      const start = new Date(new Date().getFullYear(), 0)
      return [start, end]
    },
  },
  {
    text: '过去半年',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 6)
      return [start, end]
    },
  },
]

const initData = async ()=>{
  tableLoading.value = true
  let res = await getSupervisionDataApi(
      {page: page.value, pageSize: pageSize.value,
        province:selectForm.province, city: selectForm.city,
        estimatedLevel: selectForm.estimatedLevel, isAssigned: selectForm.isAssigned,
        startTime: selectForm.dateRange == '' ? null : selectForm.dateRange[0],
        endTime: selectForm.dateRange == '' ? null : selectForm.dateRange[1]
      }
  ).catch((err)=>{
    ElMessage.error(err)
  })
  if (res?.data.code == 200){
    tableData.splice(0, tableData.length)
    tableData.push(...res.data.data.data)
    counts.value = res.data.data.total
  } else {
    ElMessage.error(res?.data.msg)
  }
  tableLoading.value = false
}

const handleAssign = (index: number, row: SupervisionDataDto)=>{
  if (row.isAssigned){
    ElMessage.warning('已指派')
  } else {
    chosenSupervisorId.value = row.id
    chosenSupervisionIsAssigned.value = row.isAssigned
    showPreview.value = true
  }
}

const estimateLevelToObj = (level: number) => {
  let option = estimatedOptions.find((item)=>{
    return item.value == level
  })
  return option ? [option] : []
}

const handlePreview = (index: number, row: SupervisionDataDto)=>{
  chosenSupervisorId.value = row.id
  showPreview.value = true
}
const handleClosePreview = (close: boolean) =>{
  if (close){
    showPreview.value = false
  }
}

const clearForm = ()=>{
  address.province = ''
  address.city = ''
  selectForm.estimatedLevel = 0
  color.value = '#33c2f1'
  selectForm.isAssigned = 0
  selectForm.dateRange = ''
}

const {page,
  pageSize,
  counts,
  tableLoading,
  handleCurrentChange,
  handleSizeChange} = usePagination(initData)

</script>

<template>
<div class="main-box">
  <el-form style="width: 100%; margin-top: 1rem" :model="selectForm" v-if="!showPreview">
    <el-row :gutter="50" style="width: 100%">
      <el-col :offset="1" :span="7">
        <el-form-item label="省区域" prop="province">
          <el-select clearable v-model="address.province" placeholder="请选择省" @change="handleProvinceSelect">
            <el-option v-for="item in provinceAndCityData" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="7">
        <el-form-item label="市区域" prop="city">
          <el-select clearable v-model="address.city" placeholder="请选择市" :disabled="!address.province || cityList.length == 0">
            <el-option v-for="item in cityList" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="7">
        <el-form-item label="预估等级" prop="estimatedLevel">
          <el-select v-model="selectForm.estimatedLevel"  @change="changeLevel">
          <el-option
              v-for="item in estimatedOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          >
            <span :style="{ color: item.color }">{{ item.label }}</span>
          </el-option>
            <template #prefix>
              <el-tag style="width: 1.5rem"  :color="color" />
            </template>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
      <el-row>
      <el-col :offset="1" :span="6">
        <el-form-item label="反馈日期" >
          <el-date-picker
              @change="console.log(selectForm.dateRange)"
              v-model="selectForm.dateRange"
              type="daterange"
              unlink-panels
              range-separator="到"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="shortcuts"
              value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-col>
      <el-col :offset="2" :span="6">
        <el-form-item >
          <el-radio-group v-model="selectForm.isAssigned" >
            <el-radio label="0" :value="0">未指派</el-radio>
            <el-radio label="1" :value="1">已指派</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
        <el-col :offset="2" :span="6">
          <el-form-item >
            <el-button type="danger" @click="clearForm">清空</el-button>
            <el-button @click="initData" type="primary">查询</el-button>
          </el-form-item>
        </el-col>
    </el-row>
  </el-form>
  <el-table  v-loading="tableLoading" :data="tableData" style="width: 90%; margin-top: 0.5rem"  stripe v-if="!showPreview">
    <el-table-column fixed sortable min-width="80" label="编号" prop="id"/>
    <el-table-column fixed label="反馈者姓名"  #default="scope">
      <span>{{scope.row.supervisor.realName}}</span>
    </el-table-column>
    <el-table-column label="所在省" #default="scope">
      <span>{{scope.row.address.province}}</span>
    </el-table-column>
    <el-table-column label="所在市" #default="scope" >
      <span>{{scope.row.address.city}}</span>
    </el-table-column>
    <el-table-column label="预估污染等级" min-width="150"  #default="scope">
      <el-tag v-for="item in estimateLevelToObj(scope.row.estimatedLevel)" :color="item.color">
        <span style="color: white">{{item.label}}</span>
      </el-tag>
    </el-table-column>
    <el-table-column label="反馈日期" min-width="100" #default="scope">
      {{scope.row.feedbackTime.substring(0, 10)}}
    </el-table-column>
    <el-table-column label="反馈时间" #default="scope">
      {{scope.row.feedbackTime.substring(11, 19)}}
    </el-table-column>
    <el-table-column label="操作" fixed="right"  align="center" min-width="200">
      <template #default="scope">
        <el-button
            icon="document"
            plain
            size="small"
            type="info"
            @click="handlePreview(scope.$index, scope.row)"
        >
        </el-button>
        <el-button plain size="small"
                   type="danger" @click="handleAssign(scope.$index, scope.row)"
                   icon="pointer"
        >
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
      v-if="!showPreview"
      class="pageList"
      :page-sizes="[5, 10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="counts"
      @size-change="handleSizeChange"
      :current-page="page"
      @current-change="handleCurrentChange">

  </el-pagination>
  <transition name="el-fade-in" mode="out-in">
    <SupervisionPreview
                   @cancel-preview="handleClosePreview"
                   v-if="showPreview"
                   :supervisor-id="chosenSupervisorId"
                   :is-assigned="chosenSupervisionIsAssigned"/>
  </transition>
</div>
</template>

<style scoped>
@import "../css/main-components.css";

</style>
